package jp.sourceforge.akjrcp.util.directorybased;

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import jp.sourceforge.akjrcp.util.ProcessPrinter;
import jp.sourceforge.akjrcp.util.image.ImageUtils;
import jp.sourceforge.akjrcp.util.image.PpmDecoder;


public class PgmToImageCommand implements DirectoryBasedCommand{
private File srcName;
private File destName;
private String imageType;

public PgmToImageCommand(File srcName, File destName,String imageType){
	this.srcName=srcName;
	this.destName=destName;
	this.imageType=imageType;
}
	public int exec() throws IOException {
		if(srcName==null || destName==null){
			return -1;
		}
	//	log.info(srcName.getName());
		FileInputStream finput=new FileInputStream(srcName);
		PpmDecoder producer=new PpmDecoder(finput);
		Image img=Toolkit.getDefaultToolkit().createImage(producer);
		
		
		
		BufferedImage tmpImage=new BufferedImage(img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_INT_RGB);
		tmpImage.getGraphics().drawImage(img, 0,0,null);
		
		if(imageType.toLowerCase().equals("jpg")||imageType.toLowerCase().equals("jpeg")){
			ImageUtils.writeJpegWithQuality(tmpImage, destName, 1.0f);	
			}else{
			ImageIO.write(tmpImage, imageType, destName);
			}
		finput.close();//how to wait?
		return 0;
	}

	public Process getProcess() {
		
		return null;
	}

	public void setProcessPrinter(ProcessPrinter processPrinter) {
		try {
			processPrinter.printOutput("pgm to "+imageType+" from "+srcName+" to "+destName+"\r\n");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
